import 'dart:convert';

import 'package:xxtea/xxtea.dart';
import 'package:convert/convert.dart' show hex;
import 'package:crypto/crypto.dart' show Digest, md5, sha256;
import 'package:encrypt/encrypt.dart';

class EncryptHelp {
  EncryptHelp._();

  /// TODO xxtea
  static String encodeXxtea(String data, String key) {
    return xxtea.encryptToString(data, key);
  }

  static String decodeXxtea(String data, String key) {
    try {
      return xxtea.decryptToString(data, key);
    } catch (e) {}
    return "";
  }

  /// TODO md5 加密
  static String generateMd5ByString(String data) {
    var content = new Utf8Encoder().convert(data);
    return generateMd5ByBytes(content);
  }

  static String generateMd5ByBytes(List<int> data) {
    var digest = md5.convert(data);
    return hex.encode(digest.bytes);
  }

  /// TODO sha256
  static String generateSha256Bytes(List<int> data) {
    Digest digest = sha256.convert(data);
    return hex.encode(digest.bytes);
  }

  static String generateSha256String(String data) {
    var content = new Utf8Encoder().convert(data);
    return generateSha256Bytes(content);
  }

  static String encodeAES(String data, String key,
      {IV iv, AESMode mode: AESMode.cbc}) {
    final encrypter = Encrypter(AES(Key.fromBase64(key), mode: mode));
    if (iv == null) {
      iv = IV.fromLength(16);
    }
    Encrypted encrypted = encrypter.encrypt(data, iv: iv);
    return hex.encode(encrypted.bytes);
  }

  static String decodeAES(String data, String key,
      {IV iv, AESMode mode: AESMode.cbc}) {
    final encrypter = Encrypter(AES(Key.fromBase64(key), mode: mode));
    if (iv == null) {
      iv = IV.fromLength(16);
    }
    return encrypter.decrypt(Encrypted(hex.decode(data)), iv: iv);
  }
}
